package com.crm.business.crm.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.crm.business.admin.mapper.AdminDeptMapper;
import com.crm.business.admin.mapper.AdminRoleMapper;
import com.crm.business.admin.mapper.AdminUserMapper;
import com.crm.business.admin.service.IAdminDeptService;
import com.crm.business.crm.mapper.BillCrmStudentPoolMapper;
import com.crm.business.crm.service.IBillCrmStudentPoolService;
import com.crm.business.servlet.BaseServiceImpl;
import com.crm.business.utils.UserUtil;
import com.crm.common.admin.entity.PO.AdminDept;
import com.crm.common.admin.entity.PO.AdminRole;
import com.crm.common.admin.entity.PO.AdminUser;
import com.crm.common.crm.entity.BO.BillStudentPoolBO;
import com.crm.common.crm.entity.PO.BillCrmStudentPool;
import com.crm.common.ka.core.common.Result;
import com.crm.common.utils.StringUtils;
import com.crm.common.utils.spring.SpringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


@Service
public class BillCrmStudentPoolServiceImpl extends BaseServiceImpl<BillCrmStudentPoolMapper, BillCrmStudentPool> implements IBillCrmStudentPoolService {


    @Autowired
    private AdminUserMapper adminUserMapper;
    @Autowired
    private AdminRoleMapper adminRoleMapper;
    @Autowired
    private AdminDeptMapper adminDeptMapper;


    @Override
    public IPage<BillCrmStudentPool> queryPageList(BillStudentPoolBO studentPoolBO) {
        IPage<BillCrmStudentPool> page = new Page<>(studentPoolBO.getPage(), studentPoolBO.getLimit());
        QueryWrapper<BillCrmStudentPool> queryWrapper = new QueryWrapper<>();
        IPage<BillCrmStudentPool> poolPage = baseMapper.selectPage(page, queryWrapper);
        List<BillCrmStudentPool> pageRecords = page.getRecords();
        List<BillCrmStudentPool> newpageRecords =new ArrayList<>();
        for (BillCrmStudentPool studentPool : pageRecords) {
            if (!StringUtils.isEmpty(studentPool.getAdminUserId())) {
                List<String> adminUserId = Arrays.asList(studentPool.getAdminUserId().split(","));
                StringBuffer sb = new StringBuffer();
                for (String id : adminUserId) {
                    QueryWrapper<AdminUser> adminUserQueryWrapper = new QueryWrapper<>();
                    adminUserQueryWrapper.select("realname").eq("user_id", id);
                    AdminUser adminUser = adminUserMapper.selectOne(adminUserQueryWrapper);
                    String realname = adminUser.getRealname();
                    sb.append(realname).append(",");

                }
                studentPool.setAdminUserName(sb.substring(0, sb.length() - 1));
            }
            if (!StringUtils.isEmpty(studentPool.getMemberUserId())) {
                List<String> deptId = Arrays.asList(studentPool.getMemberUserId().split(","));
                StringBuffer sb = new StringBuffer();
                for (String id : deptId) {
                    QueryWrapper<AdminRole> adminRoleQueryWrapper = new QueryWrapper<>();
                    adminRoleQueryWrapper.select("role_name").eq("role_id", id);
                    AdminRole adminRole = adminRoleMapper.selectOne(adminRoleQueryWrapper);
                    String name = adminRole.getRoleName();
                    sb.append(name).append(",");
                }
                studentPool.setMemberUserName(sb.substring(0, sb.length() - 1));

            }
            if (!StringUtils.isEmpty(studentPool.getMemberDeptId())) {
                List<String> deptId = Arrays.asList(studentPool.getMemberDeptId().split(","));
                StringBuffer sb = new StringBuffer();
                for (String id : deptId) {
                    QueryWrapper<AdminDept> adminRoleQueryWrapper = new QueryWrapper<>();
                    adminRoleQueryWrapper.select("name").eq("dept_id", id);
                    AdminDept adminDept = adminDeptMapper.selectOne(adminRoleQueryWrapper);
                    String name = adminDept.getName();
                    sb.append(name).append(",");
                }
                studentPool.setMemberDeptName(sb.substring(0, sb.length() - 1));
            }
            newpageRecords.add(studentPool);

        }
        return poolPage.setRecords(newpageRecords);
    }

    @Override
    public Result<BillCrmStudentPool> queryById(Integer id) {
        return Result.ok(baseMapper.selectById(id));
    }

    @Override
    public Result<Map<String, Object>> update(BillCrmStudentPool billCrmStudentPool) {
         baseMapper.updateById(billCrmStudentPool);
        return Result.ok();
    }

    /**
     * 设置VIP学员池权限
     * @param auth
     */
    @Override
    public void setStudentPoolAuth(JSONObject auth) {
        QueryWrapper<BillCrmStudentPool> queryWrapper = new QueryWrapper<BillCrmStudentPool>();
        queryWrapper.eq("status", 1);
        BillCrmStudentPool studentPool = getBaseMapper().selectOne(queryWrapper);
        List<String> roleIds = Arrays.asList(studentPool.getMemberUserId().split(","));
        List<String> deptIds = Arrays.asList(studentPool.getMemberDeptId().split(","));

        List<Integer> allDeptIds = new ArrayList<>();
        for(String deptId : deptIds){
            allDeptIds.addAll(SpringUtils.getBean(IAdminDeptService.class).queryChildDept(Integer.valueOf(deptId)));
            allDeptIds.add(Integer.valueOf(deptId));
        }

        boolean deptAuth = allDeptIds.contains(UserUtil.getUser().getDeptId()) || UserUtil.isAdmin();

        if(deptAuth){
            List<Integer> roles = UserUtil.getUser().getRoles();
            List<String> roleIdsToStr = roles.stream().map(Object::toString).collect(Collectors.toList());
            JSONObject orderPoolAuth = new JSONObject();
            orderPoolAuth.put("index",true);
            orderPoolAuth.put("receive",true);

            boolean roleAuth = isContains(roleIds, roleIdsToStr) || UserUtil.isAdmin();

            if(roleAuth){
                orderPoolAuth.put("distribution",true);
            }
            auth.getJSONObject("crm").put("vipPool",orderPoolAuth);
        }
    }

    public static boolean isContains(List<String> oneList,List<String> otherList){
        for(String other : otherList){
            if(oneList.contains(other)){
                return true;
            }
        }
        return false;
    }
}
